<template>
  <div class="justify-center">
    <div class="w-full">
      <el-upload
        ref="refElUpload"
        v-model:file-list="fileList"
        :auto-upload="true"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        :headers="Headers"
        :limit="props.limit"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-remove="onRemove"
        :on-success="onSuccess"
        :show-file-list="true"
        action="/api/common/upload"
        class="upload-demo"
        drag
        multiple
      >
        <el-button type="warning">{{ props.btnText }}</el-button>
        <div class="text-gray-400 pt-2">允许上传类型：{{ String(props.allowExtensions) }}</div>

        <!--    <template #tip>-->
        <!--      <div class="el-upload__tip">{{ props.tips }}</div>-->
        <!--    </template>-->
      </el-upload>
    </div>

    <div v-if="images.length > 0" class="mt-2 flex justify-center">
      <el-image
        :initial-index="4"
        :max-scale="7"
        :min-scale="0.1"
        :preview-src-list="images"
        :src="images[0]"
        :zoom-rate="1.2"
        fit="cover"
        style="text-align: center; width: 70px; height: 70px; margin: 0 auto"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { ElMessage, UploadFile, UploadFiles } from "element-plus";

import type { UploadProps, UploadUserFile } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { formatStaticUrl } from "@/utils/domain";

const images = ref<string[]>([]);
const Headers: Record<string, any> = {};
onMounted(() => {
  const userStore = useUserStore();
  Headers["Authorization"] = "Bearer " + userStore.token;
});

const refElUpload = ref();
const props = defineProps({
  btnText: {
    type: String,
    default: "上传文件",
    required: false
  },
  tips: {
    type: String,
    default: "请上传图片或pdf,最大10Mb",
    required: false
  },
  limit: {
    type: Number,
    default: 1,
    required: false
  },
  maxMb: {
    //最大上传mb
    type: Number,
    default: 10,
    required: false
  },
  //允许上传的后缀名
  allowExtensions: {
    type: Array<string>,
    default: [] //空数组表示不限制上传类型[".jpeg",".png"]
  }
});

const fileList = ref<UploadUserFile[]>([]);

//点击预览
const handlePreview: UploadProps["onPreview"] = uploadFile => {
  let url = uploadFile.url ?? "";
  if (!isImage(url)) {
    window.open(formatStaticUrl(url));
  }
  // if (url.includes(".pdf")) {
  //
  // }
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.error(`最多上传${files.length}个文件,请先移除已上传文件！`);
};

//上传成功
const emits = defineEmits(["fileListChange"]);
const onSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  uploadFile.url = response.data;
  filterImages();
  let fileNames = GetUploadUrls();
  emits("fileListChange", fileNames);
};

//筛选出所有图片文件
const filterImages = () => {
  // console.log(fileList.value, " ---fileList.value");
  images.value = fileList.value
    .map((s: UploadUserFile) => {
      return s.url ?? "";
    })
    .filter((url: string) => {
      return url != "" && isImage(url);
    });

  images.value = images.value.map((s: string) => formatStaticUrl(s));
};

const isImage = (fileName: string): boolean => {
  const extensions = [".jpg", ".jpeg", ".bmp", ".png", ".gif"]; // 允许上传的后缀名
  const fileExtension = fileName.slice(fileName.lastIndexOf(".")).toLowerCase(); // 获取文件后缀名，并将其转为小写
  if (extensions.includes(fileExtension)) return true;
  return false;
};
//获取所有的上传链接,数组形式
const GetUploadUrls = (): string[] => {
  let files = fileList.value
    .map((s: UploadUserFile) => {
      return s.url ?? "";
    })
    .filter((url: string) => {
      return url != "";
    });
  return files;
};

//新增一个文件到文件列表
const AppendPath = (name: string, url: string): void => {
  fileList.value.push({ name: name, url: url });
  filterImages();
};
const ClearFiles = (): void => {
  fileList.value = [];
  filterImages();
};
defineExpose({ GetUploadUrls, AppendPath, ClearFiles });

const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const fileName = rawFile.name;
  const fileExtension = fileName.slice(fileName.lastIndexOf(".")).toLowerCase(); // 获取文件后缀名，并将其转为小写
  if (!props.allowExtensions.includes(fileExtension)) {
    ElMessage.error(fileExtension + "文件是不允许上传的文件类型。" + props.tips);
    return false;
  }
  if (rawFile.size / 1024 / 1024 > props.maxMb) {
    ElMessage.error("超过最大上传大小限制：" + props.maxMb + "MB!");
    return false;
  }
  // if (props.limit == 1) {
  //   ClearFiles(); //如果仅允许上传一个 删除前清空
  // }
  return true;
};

const onRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  filterImages();
};

const beforeRemove = (uploadFile: any, uploadFiles: any): boolean => {
  return true;
};
</script>
